/**
 * @file resource.c
 * @brief Resource Interface
 *
 * @version Fixed
 * @author yemit
 * @date 2012-09-17
 */
#include <stdint.h>
#include "resource.h"
#include "module.h"
#include "flash.h"
#include <sys/ioctl.h>
#include <string.h>
#include "config.h"

extern int verify_firmware2(part_t * ppart);

part_t * res_part = NULL;

#ifdef CONFIG_FONT_SIZE12
res_entry_t font_hzk12;
res_entry_t font_asc12;
#endif

#ifdef CONFIG_FONT_SIZE16
res_entry_t font_hzk16;
res_entry_t font_asc16;
#endif

#ifdef CONFIG_FONT_SIZE24

#ifdef CONFIG_STAR_NET_FONT
res_entry_t star_net_font;
#else
res_entry_t font_hzk24;
res_entry_t font_asc24;
#endif

#endif //#ifdef CONFIG_FONT_SIZE24


int find_resource_by_id(uint32_t id, res_entry_t * res)
{
        uint32_t offset = 256;
        res_entry_t tmp;

        do { 
                if (part_read(res_part, offset, &tmp, sizeof(tmp))
                                != sizeof(tmp))
                        return -1;
    
                if (tmp.id == id) {
                        memcpy(res, &tmp, sizeof (tmp));
                        res->offset += 256;
                        return 0;
                }
                else if (tmp.flag == RES_FLG_END) break;     
                offset = tmp.offset + tmp.size + 256;
        }while (1);
        return -1;
}

int resource_init(void)
{
   
#ifndef CONFIG_FONT_NO 
        if ((res_part = get_part_by_name("resource", NULL)) == NULL)
                return -1;
        if (!verify_firmware2(res_part))
			return -2;
#ifdef CONFIG_FONT_SIZE12
        if (find_resource_by_id(RES_ID_FONT_ASC12, &font_asc12) < 0) {
                return -3;
        }
        if (find_resource_by_id(RES_ID_FONT_HZK12, &font_hzk12) < 0) {
                return -4;
        }
#endif

#ifdef CONFIG_FONT_SIZE16
        if (find_resource_by_id(RES_ID_FONT_ASC16, &font_asc16) < 0){
                return -5;
        }
        if (find_resource_by_id(RES_ID_FONT_HZK16, &font_hzk16) < 0) {
                return -6;
        }
#endif

#ifdef CONFIG_FONT_SIZE24 
 #ifdef CONFIG_STAR_NET_FONT        
        if (find_resource_by_id(RES_ID_STAR_NET_FONT, &star_net_font) < 0)
                return -7;
 #else
        if (find_resource_by_id(RES_ID_FONT_ASC24, &font_asc24) < 0)
                return -8;
        if (find_resource_by_id(RES_ID_FONT_HZK24, &font_hzk24) < 0)
                return -9;
 #endif  
#endif //#ifdef CONFIG_FONT_SIZE24 


#endif  //#ifndef CONFIG_FONT_NO 

        return 0;
}

void get_resource_by_id(res_entry_t * res, uint8_t * buf)
{
        part_read(res_part, res->offset, buf, res->size);
}

